import { locationAPI } from '../api';

/**
 * 天气代码转表情符号
 * @param {number} code 天气代码
 * @returns {string} 表情符号
 */
export function weatherCodeToEmoji(code) {
  if (code === 0) return '☀️';
  if ([1, 2, 3].includes(code)) return '🌤️';
  if ([45, 48].includes(code)) return '🌫️';
  if ([51, 53, 55, 56, 57].includes(code)) return '🌦️';
  if ([61, 63, 65, 66, 67, 80, 81, 82].includes(code)) return '🌧️';
  if ([71, 73, 75, 85, 86].includes(code)) return '❄️';
  if ([95, 96, 99].includes(code)) return '⛈️';
  return '☁️';
}

/**
 * 根据天气描述确定天气代码
 * @param {string} weatherDesc 天气描述
 * @returns {number} 天气代码
 */
export function getWeatherCodeFromDescription(weatherDesc) {
  if (!weatherDesc) return 0;

  if (weatherDesc.includes('晴')) {
    return 0;
  } else if (weatherDesc.includes('云')) {
    return 1;
  } else if (weatherDesc.includes('雨')) {
    return 61;
  } else if (weatherDesc.includes('雪')) {
    return 71;
  }

  return 0;
}

/**
 * 获取城市天气信息
 * @param {string} city 城市名称
 * @param {string} adcode 城市编码
 * @returns {Promise<Object|null>} 天气信息
 */
export async function fetchWeatherByCity(city, adcode) {
  try {
    
    // 必须有adcode才能调用API
    if (!adcode) {
      return null;
    }

    const weatherResp = await locationAPI.getActualWeather(adcode);
    
    const weatherData = weatherResp?.data?.data || weatherResp?.data;

    if (weatherData?.weather) {
      const actualWeather = weatherData.weather;
      const temp = actualWeather.temperature;
      const weatherDesc = actualWeather.weather;
      const windDirection = actualWeather.winddirection;
      const windPower = actualWeather.windpower;
      const humidity = actualWeather.humidity;
      const reportTime = actualWeather.reporttime;

      // 根据天气描述确定天气代码
      const weatherCode = getWeatherCodeFromDescription(weatherDesc);

      const result = {
        temp: temp ? Math.round(parseFloat(temp)) : null,
        icon: weatherCodeToEmoji(weatherCode),
        description: weatherDesc,
        windDirection: windDirection,
        windPower: windPower,
        humidity: humidity,
        reportTime: reportTime,
        source: 'api',
      };

      return result;
    } else {
    }

    return null;
  } catch (error) {
    console.error('[weatherUtils] 获取天气数据异常:', error.message || error);
    return null;
  }
}
